//
//  HMTabBarContentView.m
//  01-HMTabBarContentView控件开发
//
//  Created by teacher on 2017/7/23.
//  Copyright © 2017年 teacher. All rights reserved.
//

#import "HMTabBarContentView.h"
#import <Masonry/Masonry.h>

@interface HMTabBarContentView () <UIScrollViewDelegate>

// 选项条父视图容器
@property (strong, nonatomic)   UIScrollView                *tabBar;

// 内容父视图容器
@property (strong, nonatomic)   UIScrollView                *contentScrollView;

// 选项容器
@property (strong, nonatomic)   NSMutableArray<UIButton *>  *tabBarItems;

// 内容容器
@property (strong, nonatomic)   NSMutableArray<UIView *>    *contents;

// 当前选中按钮
@property (strong, nonatomic)   UIButton                    *selectedItemButton;

// 选中视图的容器
@property (strong, nonatomic)   UIView                      *selectedHighlightViewContainer;


@end

@implementation HMTabBarContentView

#pragma mark - 属性重写 -
- (NSMutableArray<UIButton *> *)tabBarItems {
    if(_tabBarItems == nil) {
        _tabBarItems = [NSMutableArray array];
    }
    return _tabBarItems;
}

- (NSMutableArray<UIView *> *)contents {
    if(_contents == nil) {
        _contents = [NSMutableArray array];
    }
    return _contents;
}

#pragma mark - 私有方法 -

// 返回 TabBar 高度
- (float)tabBarHeight {
    // 定义选项条的高度
    float tabBarHeight = 50;
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(tabBarHeightInTabBarContentView:)]) {
        tabBarHeight = [self.delegate tabBarHeightInTabBarContentView:self];
    }
    return  tabBarHeight;
}

// 返回数量
- (NSInteger)numberOfItems {
    NSInteger count = 0;
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(numberOfItemsInTabBarContentView:)]) {
        count = [self.dataSource numberOfItemsInTabBarContentView:self];
    }
    return count;
}

#pragma mark - 公共方法 -
/**
 刷新界面
 */
- (void)reloadData {
    
    // 定义选项条的高度
    float tabBarHeight = [self tabBarHeight];
    
    // 创建2个容器
    if(self.tabBar == nil) {
        self.tabBar = [UIScrollView new];
        self.tabBar.showsHorizontalScrollIndicator = NO;
        self.tabBar.showsVerticalScrollIndicator = NO;
        self.tabBar.backgroundColor = [UIColor purpleColor];
        [self addSubview:self.tabBar];
        [self.tabBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self);
            make.height.mas_equalTo(tabBarHeight);
        }];
    }
    
    if(self.contentScrollView == nil) {
        self.contentScrollView = [UIScrollView new];
        self.contentScrollView.pagingEnabled = YES;
        self.contentScrollView.showsVerticalScrollIndicator = NO;
        self.contentScrollView.showsHorizontalScrollIndicator = NO;
        self.contentScrollView.backgroundColor = [UIColor greenColor];
        self.contentScrollView.delegate = self;
        [self addSubview:self.contentScrollView];
        [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self);
            make.top.equalTo(self.tabBar.mas_bottom);
        }];
    }
    
    // 布局
    [self.tabBar mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self);
        make.height.mas_equalTo(tabBarHeight);
    }];
    
    [self.contentScrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self);
        make.top.equalTo(self.tabBar.mas_bottom);
    }];
    
    // 在构建之前先清空
    for (UIButton *button in self.tabBarItems) {
        [button removeFromSuperview];
    }
    
    for (UIView *content in self.contents) {
        [content removeFromSuperview];
    }
    
    
    NSInteger count = [self numberOfItems];
    
    UIColor *selectedTabBarItemColor = [UIColor orangeColor];
    if(self.delegate && [self.delegate respondsToSelector:@selector(selectedTabBarItemTitleColorInTabBarContentView:)]) {
        selectedTabBarItemColor = [self.delegate selectedTabBarItemTitleColorInTabBarContentView:self];
    }
    
    // 构建 tabBar 选项的按钮
    for (NSInteger i = 0; i < count; i ++) {
        UIButton *tabBarItemButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        // 设置属性
        NSString *title = @"";
        if(self.dataSource && [self.dataSource respondsToSelector:@selector(tabBarContentView:titleForItemAtIndex:)]) {
            title = [self.dataSource tabBarContentView:self titleForItemAtIndex:i];
        }
        
        [tabBarItemButton setTitle:title forState:UIControlStateNormal];
        [tabBarItemButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [tabBarItemButton setTitleColor:selectedTabBarItemColor forState:UIControlStateSelected];
        [tabBarItemButton addTarget:self action:@selector(actionSelectButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.tabBar addSubview:tabBarItemButton];
        [self.tabBarItems addObject:tabBarItemButton];
        
    }
    
    CGFloat precent = 1.0 / count;
    
    // 布局按钮
    for (NSInteger i = 0; i < count; i ++) {
        UIButton *tabBarItemButton = self.tabBarItems[i];
        
        [tabBarItemButton mas_makeConstraints:^(MASConstraintMaker *make) {
            if(i == 0) {
                make.left.equalTo(self.tabBar);
                make.top.bottom.equalTo(self.tabBar);
                if(count > 1) {
                    make.right.equalTo(self.tabBarItems[i + 1].mas_left);
                } else {
                    make.right.equalTo(self.tabBar);
                }
            } else if(i == count - 1) {
                make.top.bottom.equalTo(self.tabBar);
                make.right.equalTo(self.tabBar);
                if(count > 1) {
                    make.left.equalTo(self.tabBarItems[i - 1].mas_right);
                }
            } else {
                make.top.bottom.equalTo(self.tabBar);
                make.left.equalTo(self.tabBarItems[i - 1].mas_right);
                make.right.mas_equalTo(self.tabBarItems[i + 1].mas_left);
            }
            make.width.equalTo(self.tabBar.mas_width).multipliedBy(precent);
            make.height.equalTo(self.tabBar.mas_height);
        }];
    }
    
    
    
    
    
    // 构建内容
    for (NSInteger i = 0; i < count; i ++) {
        UIView *contentView = nil;
        if(self.dataSource && [self.dataSource respondsToSelector:@selector(tabBarContentView:contentForItemAtIndex:)]) {
            contentView = [self.dataSource tabBarContentView:self contentForItemAtIndex:i];
        }
        if(contentView == nil) {
            contentView = [UIView new];
        }
        
        [self.contentScrollView addSubview:contentView];
        [self.contents addObject:contentView];
    }
    
    // 布局内容
    for (NSInteger i = 0; i < count; i ++) {
        UIView *contentView = self.contents[i];
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            if(i == 0) {
                make.left.equalTo(self.contentScrollView);
                make.top.bottom.equalTo(self.contentScrollView);
                if(count > 1) {
                    make.right.equalTo(self.contents[i + 1].mas_left);
                } else {
                    make.right.equalTo(self.contentScrollView);
                }
            } else if(i == count - 1) {
                make.top.bottom.equalTo(self.contentScrollView);
                make.right.equalTo(self.contentScrollView);
                if(count > 1) {
                    make.left.equalTo(self.contents[i - 1].mas_right);
                }
            } else {
                make.top.bottom.equalTo(self.contentScrollView);
                make.left.equalTo(self.contents[i - 1].mas_right);
                make.right.mas_equalTo(self.contents[i + 1].mas_left);
            }
            make.width.equalTo(self.contentScrollView.mas_width);
            make.height.equalTo(self.contentScrollView.mas_height);
        }];
    }
    
    if(count > 0) {
        
        [self actionSelectButton:self.tabBarItems[0]];
        
        // 添加一个高亮的视图层,表示选中状态
        if(self.selectedHighlightViewContainer == nil) {
            self.selectedHighlightViewContainer = [UIView new];
            self.selectedHighlightViewContainer.backgroundColor = [UIColor clearColor];
            self.selectedHighlightViewContainer.userInteractionEnabled = NO;
            [self.tabBar insertSubview:self.selectedHighlightViewContainer atIndex:0];
            [self.selectedHighlightViewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.selectedItemButton);
            }];
        }
        
        NSArray *subviews = [self.selectedHighlightViewContainer subviews];
        for (UIView *view in subviews) {
            [view removeFromSuperview];
        }
        
        if(self.delegate && [self.delegate respondsToSelector:@selector(selectedTabBarItemBackgroundInTabBarContentView:)]) {
            UIView *bgView = [self.delegate selectedTabBarItemBackgroundInTabBarContentView:self];
            [self.selectedHighlightViewContainer addSubview:bgView];
            [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self.selectedHighlightViewContainer);
            }];
            
        }
    }
}

- (IBAction)actionSelectButton:(UIButton *)sender {
    if(self.selectedItemButton == sender) return;
    
    if(self.selectedItemButton != nil) {
        self.selectedItemButton.selected = NO;
        self.selectedItemButton = nil;
    }
    
    self.selectedItemButton = sender;
    
    // 获取计算选中索引
    NSInteger selectedIndex = [self.tabBarItems indexOfObject:self.selectedItemButton];
    CGFloat offsetX = self.contentScrollView.frame.size.width * selectedIndex;
    [self.contentScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
    
    [self.selectedHighlightViewContainer mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.selectedItemButton);
        
    }];
    self.selectedItemButton.selected = YES;
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(tabBarContentView:didSelectContentAtIndex:)]) {
        [self.delegate tabBarContentView:self didSelectContentAtIndex:selectedIndex];
    }
    
    
    
}

#pragma mark - UIScrollViewDelegate -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if(scrollView == self.contentScrollView) {
        // 比例是相等的
        // 当前导航条的OffsetX / 当行条的OffsetX 最大范围 == 当前内容的 OffsetX / 内容的 OffsetX 最大范围
        
        CGFloat tabBarOffsetX = self.contentScrollView.contentOffset.x / (self.contentScrollView.contentSize.width - self.contentScrollView.frame.size.width) * (self.tabBar.contentSize.width - self.selectedItemButton.frame.size.width);
        
        CGRect newFrame = self.selectedHighlightViewContainer.frame;
        newFrame.origin.x = tabBarOffsetX;
        self.selectedHighlightViewContainer.frame = newFrame;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if(scrollView == self.contentScrollView) {
        NSInteger selectedIndex = self.contentScrollView.contentOffset.x / self.contentScrollView.frame.size.width;
        [self actionSelectButton:self.tabBarItems[selectedIndex]];
    }
}

@end
